import arrow

from pymongo import MongoClient

from conf.settings import CLOUDMONITOR_MONGODB, CLOUDMONITOR_DB

db = MongoClient(CLOUDMONITOR_MONGODB)[CLOUDMONITOR_DB]


def main():
    pipeline = [
        {'$match': {'planExpireTime': {'$exists': 1}}},
        {'$lookup': {'from': 'users', 'localField': 'uid', 'foreignField': '_id', 'as': 'user'}},
        {'$unwind': '$user'},
        {'$lookup': {'from': 'packages', 'localField': 'planId', 'foreignField': '_id', 'as': 'package'}},
        {'$unwind': '$package'},
        {'$project': {'_id': 0, 'username': '$user.username', 'email': '$user.email', 'packname': '$package.name', 'planExpireTime': 1}}
    ]

    title = False
    with open('./users.csv', 'w', encoding='utf-8') as f:
        for item in db['balances'].aggregate(pipeline):
            item['planExpireTime'] = arrow.get(item['planExpireTime']).isoformat()
            if not title:
                f.writelines(','.join(list(item.keys())))
                f.writelines('\n')
                title = True
            f.writelines(','.join(list(item.values())))
            f.writelines('\n')


if __name__ == '__main__':
    main()
